package com.zbl.zblproject.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.demo.trade.utils.ExcelUtil;
import com.alipay.demo.trade.utils.GoodDateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.contract.entity.Contract;
import com.zbl.zblproject.contract.entity.Rebates;
import com.zbl.zblproject.contract.mapper.ContractMapper;
import com.zbl.zblproject.contract.mapper.RebatesMapper;
import com.zbl.zblproject.core.entity.RechargeLog;
import com.zbl.zblproject.core.entity.Supplier;
import com.zbl.zblproject.core.mapper.AdminUserMapper;
import com.zbl.zblproject.core.mapper.RechargeLogMapper;
import com.zbl.zblproject.core.mapper.SupplierMapper;
import com.zbl.zblproject.core.service.SupplierService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import com.zbl.zblproject.erp.entity.ErpCategory;
import com.zbl.zblproject.erp.entity.ErpGoods;
import com.zbl.zblproject.erp.entity.ErpOrder;
import com.zbl.zblproject.erp.entity.Goods;
import com.zbl.zblproject.erp.mapper.ErpOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/12
 * 供应商数据层
 */
@Service
@Transactional
public class SuplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private RechargeLogMapper rechargeLogMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private RebatesMapper rebatesMapper;

    @Autowired
    private ErpOrderMapper erpOrderMapper;
    private Logger logger = LoggerFactory.getLogger(SupplierService.class);


    @Override
    public String export(HttpServletResponse response, String ids) {
        try {
            QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("suppliers_id",ids);
            List<Supplier> suppliers = supplierMapper.selectList(queryWrapper);
            String fileName="suppliers";
            List<Map<String,Object>> list=createExcelRecord(suppliers);
            String columnNames[] = {"供货商名称","地址","开户信息","合同开始时间","合同结束时间","签约类型","合同返点","物流模式","","","","","","",""};//列名
            String keys[] = {"goodsName","catName","supName"};//map中的key
            ExcelUtil.downloadWorkBook(list,keys,columnNames,fileName,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "excel";
    }

    /**
     * 创建Excel表中的记录
     * @param
     * @return
     */
    private List<Map<String, Object>> createExcelRecord(List<Supplier> suppliers){
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sheetName", "商品信息表");
            listmap.add(map);
            for (int j = 0; j < suppliers.size(); j++) {
                Supplier supplier=suppliers.get(j);
                Map<String, Object> mapValue = new HashMap<String, Object>();
//                mapValue.put("goodsName",orderItemDTO.getGoodsName());
//                mapValue.put("catName",orderItemDTO.getCatName());
//                mapValue.put("supName",orderItemDTO.getSupName());
                listmap.add(mapValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listmap;
    }

    public IPage<Supplier> erpSupperList(int current, int size) {
        Page page = new Page(current, size);
        return supplierMapper.selectPage(page);
    }


    @Override
    public boolean deleteSuppliers(List<Integer> ids) {
        return ids.size() == supplierMapper.deleteBatchIds(ids);
    }


    @Override
    public boolean updateSupplier(Supplier supplier) {
        Supplier supplier1 = supplierMapper.selectById(supplier.getSuppliersId());
        if (1 == supplierMapper.updateById(supplier)){
            if (supplier1.getLogisticsCostRatio().doubleValue()!=supplier.getLogisticsCostRatio().doubleValue()){
                List<ErpOrder> erpOrders = erpOrderMapper.selectBySupId(supplier.getSuppliersId());
                for (ErpOrder erpOrder:erpOrders){
                    erpOrder.setLogisticsCostRatio(supplier.getLogisticsCostRatio());
                    erpOrderMapper.updateById(erpOrder);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Supplier addSupplier(Supplier supplier, String json) {
        JSONObject object = JSONObject.parseObject(json);
        if (object.getString("number") != null && !"".equals(object.getString("number"))) {
            supplier.setStartTime(GoodDateUtil.dateToStamps(object.getString("startTime")) / 1000);
            supplier.setEndTime(GoodDateUtil.dateToStamps(object.getString("endTime")) / 1000);
        }
        int i = supplierMapper.insert(supplier);
        Preconditions.checkArgument(i == 1, "更新供应商失败");

        if (object.getString("number") != null && !"".equals(object.getString("number"))) {

            //添加合同信息
            Contract contract = new Contract();
            contract.setNumber(object.getString("number"));


            Supplier suppliers = supplierMapper.selectSupplierByName(supplier.getSuppliersName());
            if (suppliers != null) {
                contract.setSuppliersName(suppliers.getSuppliersName());
                contract.setSuppliersAddress(suppliers.getSuppliersAddr());
                contract.setSuppliersDesc(suppliers.getSuppliersDesc());
                contract.setSuppliersTelephone(suppliers.getHeadNumber());
                contract.setSupplierId(suppliers.getSuppliersId());
            }

            try {
                contract.setAddTime(LocalDateTime.now());
                contract.setStartTime(TimeUtil.parseTime(object.getString("startTime")));
                contract.setEndTime(TimeUtil.parseTime(object.getString("endTime")));
                contract.setCashBack(object.getDouble("cashBack"));
                contract.setPurchasesHighest(object.getDouble("purchasesHighest"));
                contract.setRebatesHighest(object.getDouble("rebatesHighest"));
                contract.setPlanRebatesHighest(object.getDouble("planRebatesHighest"));
                contract.setPurchasesLowest(object.getDouble("purchasesLowest"));
                contract.setRebatesLowest(object.getDouble("rebatesLowest"));
                contract.setPlanRebatesLowest(object.getDouble("planRebatesLowest"));
                contract.setNote(object.getString("note"));
                contract.setComment(object.getString("comment"));
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            List<Rebates> rebates = object.getJSONArray("rebates").toJavaList(Rebates.class);
            boolean result = false;
            result = contractMapper.insert(contract) == 1;
            if (result) {
                for (Rebates rebate : rebates) {
                    rebate.setContractId(contract.getContractId());
                    rebatesMapper.insert(rebate);
                }
            }
        }
        return supplier;
    }

    @Override
    public Supplier getOneById(int id) {
        Supplier supplier = supplierMapper.selectById(id);
        supplier.setStartTime(supplier.getStartTime() * 1000);
        supplier.setEndTime(supplier.getEndTime() * 1000);
        return supplier;
    }


    @Override
    public RechargeLog recharge(int supplierId, int operatorId, double price, String remarks, String imgPath) {
        Supplier supplier = supplierMapper.selectById(supplierId);
        Preconditions.checkNotNull(supplier, "未查询到供应商!");
        BigDecimal money = BigDecimal.valueOf(price);
        RechargeLog log = new RechargeLog();
        log.setMoney(money);
        log.setBeforeMoney(supplier.getBalance());
        log.setTime(LocalDateTime.now());
        log.setUserId(supplierId);
        log.setOperatorName(adminUserMapper.selectNameById(operatorId));
        log.setMode(1);
        log.setImgPath(imgPath);
        log.setRemarks(remarks);
        rechargeLogMapper.insert(log);
        logger.info("supplierID:{}, 减去金额:{}", supplier.getSuppliersId(), money);
        if (supplierMapper.deleteSuplierBalance(supplier.getSuppliersId(), money)) {
            return log;
        }
        return null;
    }

    @Override
    public IPage<RechargeLog> logPage(int supplierId, int current, int size) {
        QueryWrapper<RechargeLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", supplierId).eq("mode", 1);
        IPage<RechargeLog> page = new Page<>(current, size);
        return rechargeLogMapper.selectPage(page, wrapper);
    }

    @Override
    public String flowCode(String token) {
        StringBuilder sb = new StringBuilder();
        Random randdata = new Random();
        Random rand = new Random();
        int data = 0;
        for (int i = 0; i < 3; i++) {
            int index = rand.nextInt(3);
            // 目的是随机选择生成数字，大小写字母
            switch (index) {
                case 0:
                    data = randdata.nextInt(10);// 仅仅会生成0~9
                    sb.append(data);
                    break;
                case 1:
                    data = randdata.nextInt(26) + 65;// 保证只会产生65~90之间的整数
                    sb.append((char) data);
                    break;
                case 2:
                    data = randdata.nextInt(26) + 97;// 保证只会产生97~122之间的整数
                    sb.append((char) data);
                    break;
            }
        }
        String result = sb.toString();
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.eq("factory_make", result);
        Supplier supplier = supplierMapper.selectOne(wrapper);
        if (supplier != null) {
            throw new RuntimeException("供应商编号重复!");
        }
        return token + result;
    }
}
